/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-07 13:44:18
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.controller;

import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.joysuch.wwyt.bp.bean.*;
import com.joysuch.wwyt.bp.bean.BpEmergencyContingencyPlanListBean.Search;
import com.joysuch.wwyt.bp.entity.BpEmergencyContingencyPlan;
import com.joysuch.wwyt.bp.entity.BpEmergencyContingencyType;
import com.joysuch.wwyt.bp.entity.BpEmergencyContingencyPlans;
import com.joysuch.wwyt.bp.entity.BpEmergencyPeople;
import com.joysuch.wwyt.bp.enums.RegulationDocumentTypes;
import com.joysuch.wwyt.bp.service.BpEmergencyContingencyPlanService;
import com.joysuch.wwyt.core.bean.BaseAttachmentBean;
import com.joysuch.wwyt.core.bean.BaseConfigBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 应急消防管理——预案
 */
@RestController
@RequestMapping("/wwyt/bp-emergency-contingency-plan")
@Api(tags = "应急消防管理-预案")
public class BpEmergencyContingencyPlanController {

    private static final Logger logger = LoggerFactory.getLogger(BpEmergencyContingencyPlanController.class);

    @Autowired
    private BpEmergencyContingencyPlanService bpEmergencyContingencyPlanService;

    /**
     * 添加预案
     *
     * @param entity           待添加的预案信息
     * @param //attachmentJson 待上传的附件相关JSON
     */
    @RequestMapping("add")
    public Object add(@Valid @RequestBody BpEmergencyContingencyPlanEditBean entity) {
        try {
            validateMakeStartEndTime(entity);
            String attachmentIds = extractAttachmentIds(entity);
            entity.setAttachmentId(attachmentIds);
            bpEmergencyContingencyPlanService.add(entity);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("创建失败", e);
            return ResultBean.fail(101, e.getMessage());
        }
    }

    /**
     * @param entity
     */
    protected void validateMakeStartEndTime(BpEmergencyContingencyPlanEditBean entity) {
        if (entity.getMakeTimeStart() != null && entity.getMakeTimeEnd() != null
                && entity.getMakeTimeStart().after(entity.getMakeTimeEnd())) {
            throw new IllegalArgumentException("开始日期必须在结束日期之后");
        }
    }

    /**
     * @param entity
     */
    protected String extractAttachmentIds(@Valid BpEmergencyContingencyPlanEditBean entity) {
        if (entity.getBaseAttachmentBean() != null && entity.getBaseAttachmentBean().size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (BaseAttachmentBean a : entity.getBaseAttachmentBean()) {
                sb.append(a.getId()).append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        }
        return null;
    }

    /**
     * 修改预案
     *
     * @param entity           待修改的预案信息
     * @param //attachmentJson 待修改的附件相关JSON （可不传）
     */
    @RequestMapping("update")
    public Object update(@Valid @RequestBody BpEmergencyContingencyPlanEditBean entity) {
        try {
            if (entity.getId() == null) {
                return ResultBean.fail(102, "未指定主键");
            }
            validateMakeStartEndTime(entity);
            String attachmentIds = extractAttachmentIds(entity);
            entity.setAttachmentId(attachmentIds);
            bpEmergencyContingencyPlanService.update(entity);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("更新失败：#" + entity.getId(), e);
            return ResultBean.fail(101, "更新失败");
        }
    }

    /**
     * 获取预案信息（分页）
     *
     * @param page      分页信息
     * @param condition 筛选条件
     */
    @RequestMapping("page")
    public Object page(Pageable page, Search condition) {
        try {
            Page<BpEmergencyContingencyPlanListBean> data = bpEmergencyContingencyPlanService.findByPage(page,
                    condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    /**
     * 删除预案
     *
     * @param id 待删除预案 ID
     */
    @RequestMapping("delete")
    public Object delete(Long id) {
        try {
            bpEmergencyContingencyPlanService.delete(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

    @RequestMapping("get")
    public Object getById(@Valid @NotNull(field = "id") Long id) {
        try {
            return ResultBean.success(bpEmergencyContingencyPlanService.getById(id));
        } catch (Exception e) {
            logger.error("查询详情失败", e);
            return ResultBean.fail(101, "查询详情失败:" + e.getMessage());
        }
    }

    /**
     * 提交审核
     *
     * @param id 指定预案 ID
     */
    @GetMapping("/submitAudit")
    @ApiOperation(value = "提交审核")
    @RequiresPermissions("bp:contingency:submitAudit")
    public Object submitAudit(Long id) {
        try {
            //BpEmergencyContingencyPlan tempPlan = bpEmergencyContingencyPlanService.findById(id);
            BpEmergencyContingencyPlans tempPlan = bpEmergencyContingencyPlanService.findById(id);
            if (tempPlan.getState() != RegulationDocumentTypes.TO_BE_AUDITED.getId()) {
                return ResultBean.fail(102, "文档状态错误");
            }
            bpEmergencyContingencyPlanService.changeState(id, null, null);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("提交审核失败", e);
            return ResultBean.fail(101, "提交审核失败");
        }
    }

    /**
     * 审核[通过/不通过]
     *
     * @param id          指定审核文档 ID
     * @param isPass      是否通过（true:通过；false:不通过）
     * @param auditRemark 审核意见
     */
    @RequestMapping("/audit")
    @ApiOperation(value = "审核")
    @RequiresPermissions("bp:contingency:audit")
    public Object audit(Long id, Boolean isPass, String auditRemark) {
        try {
            BpEmergencyContingencyPlans tempPlan = bpEmergencyContingencyPlanService.findById(id);
            if (tempPlan.getState() != RegulationDocumentTypes.AUDIT_WAIT.getId()) {
                return ResultBean.fail(102, "文档状态错误");
            }
            bpEmergencyContingencyPlanService.changeState(id, isPass, auditRemark);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("审核操作失败", e);
            return ResultBean.fail(101, "审核操作失败");
        }
    }

    @PostMapping("/addType")
    @ApiOperation(value = "新增预案类型")
    @RequiresPermissions("bp:contingency:addType")
    public ResultBean addType(@RequestBody BpEmergencyContingencyTypeBean bean) {
        BpEmergencyContingencyType save = bpEmergencyContingencyPlanService.addType(bean);
        return ResultBean.success(save);

    }

    @PostMapping("/uodateType")
    @ApiOperation(value = "修改预案类型")
    @RequiresPermissions("bp:contingency:uodateType")
    public ResultBean updateType(@RequestBody BpEmergencyContingencyTypeBean bean) {
        BpEmergencyContingencyType save = bpEmergencyContingencyPlanService.updateType(bean);
        return ResultBean.success(save);
    }

    @GetMapping("/deleteType")
    @ApiOperation(value = "删除预案类型")
    @RequiresPermissions("bp:contingency:deleteType")
    public ResultBean deleteType(Long id) {
        try {
            bpEmergencyContingencyPlanService.deleteType(id);
            return ResultBean.success("");
        } catch (Exception e) {
            return ResultBean.fail(101, "删除失败");
        }
    }

    @GetMapping("/pageType")
    @ApiOperation(value = "分页展示预案类型")
//    @RequiresPermissions("bp:contingency:pageType")
    public ResultBean pageType(Pageable page, BpEmergencyContingencyTypeBean.SearchType condition) {
        try {
            Page<BpEmergencyContingencyTypeBean> data = bpEmergencyContingencyPlanService.pageType(page, condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }


    @GetMapping("/findTypeList")
    @ApiOperation(value = "获取预案类型列表")
//    @RequiresPermissions("bp:contingency:findTypeList")
    public ResultBean findTypeList() {
        List<BpEmergencyContingencyType> list = bpEmergencyContingencyPlanService.findTypeList();
        return ResultBean.success(list);
    }


    @PostMapping("/addPlan")
    @ApiOperation(value = "新增预案")
    @RequiresPermissions("bp:contingency:addPlan")
    public ResultBean addPlan(@RequestBody BpEmergencyContingencyPlansBean bean) {
        BpEmergencyContingencyPlans save = bpEmergencyContingencyPlanService.addPlan(bean);
        return ResultBean.success(save);
    }

    @PostMapping("/updatePlan")
    @ApiOperation(value = "修改预案")
    @RequiresPermissions("bp:contingency:updatePlan")
    public ResultBean updatePlan(@RequestBody BpEmergencyContingencyPlansBean bean) {
        BpEmergencyContingencyPlans save = bpEmergencyContingencyPlanService.updatePlan(bean);
        return ResultBean.success(save);
    }

    @GetMapping("/deletePlan")
    @ApiOperation(value = "删除预案")
    @RequiresPermissions("bp:contingency:deletePlan")
    public ResultBean deletePlan(Long id) {
        bpEmergencyContingencyPlanService.deletePlan(id);
        return ResultBean.success("");
    }

    @GetMapping("/getPlan")
    @ApiOperation(value = "查看预案")
//    @RequiresPermissions("bp:contingency:getPlan")
    public ResultBean getPlan(Long id) {
        try {
            BpEmergencyContingencyPlansBean pBean = bpEmergencyContingencyPlanService.getPlan(id);
            return ResultBean.success(pBean);
        } catch (Exception e) {
            return null;
        }
    }

    @GetMapping("/rePlan")
    @ApiOperation(value = "重新编制预案")
    @RequiresPermissions("bp:contingency:rePlan")
    public ResultBean rePlan(Long id) {
        try {
            BpEmergencyContingencyPlans plan = bpEmergencyContingencyPlanService.findById(id);
            if (plan.getState() != RegulationDocumentTypes.AUDIT_PASS.getId()) {
                return ResultBean.fail(102, "预案未审核通过");
            }
            bpEmergencyContingencyPlanService.rePlan(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("重新编制失败", e);
            return ResultBean.fail(101, "重新编制失败");
        }
    }

    @GetMapping("/pagePlan")
    @ApiOperation(value = "分页展示预案")
    public ResultBean pagePlan(Pageable page, BpEmergencyContingencyPlansBean.SearchPlanBean condition) {
        try {
            Page<BpEmergencyContingencyPlansBean> data = bpEmergencyContingencyPlanService.pagePlan(page, condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    //应急人员管理
    @PostMapping("/addPeople")
    @ApiOperation(value = "增加应急人员")
    @RequiresPermissions("bp:contingency:addPeople")
    public ResultBean addPeople(@RequestBody @Validated BpEmergencyPeopleBean bean) {
        BpEmergencyPeople save = bpEmergencyContingencyPlanService.addPeople(bean);
        return ResultBean.success(save);
    }


    @PostMapping("/updatePeople")
    @ApiOperation(value = "修改应急人员")
    @RequiresPermissions("bp:contingency:updatePeople")
    public ResultBean updatePeople(@RequestBody @Validated BpEmergencyPeopleBean bean) {
        BpEmergencyPeople save = bpEmergencyContingencyPlanService.updatePeople(bean);
        return ResultBean.success(save);
    }

    @GetMapping("/getPeopleById")
    @ApiOperation(value = "查看应急人员")
    public ResultBean getPeopleById(@RequestParam(value = "id") Long id) {
        BpEmergencyPeopleBean bean = bpEmergencyContingencyPlanService.getPeopleById(id);
        return ResultBean.success(bean);
    }

    @GetMapping("/pagePeople")
    @ApiOperation(value = "分页展示应急人员")
    public ResultBean pagePeople(Pageable page, BpEmergencyPeopleBean.SearchPlanBean condition) {
        try {
            Page<BpEmergencyPeopleBean> data = bpEmergencyContingencyPlanService.pagePeople(page, condition);
            return ResultBean.pageData(data.getContent(), data.getTotalElements());
        } catch (Exception e) {
            logger.error("分页查询失败", e);
            return ResultBean.fail(101, "分页查询失败");
        }
    }

    @GetMapping("/deletePeople")
    @ApiOperation(value = "删除应急人员")
    @RequiresPermissions("bp:contingency:deletePeople")
    public ResultBean deletePeople(@RequestParam(value = "id") Long id) {
        try {
            bpEmergencyContingencyPlanService.deletePeople(id);
            return ResultBean.success("");
        } catch (Exception e) {
            logger.error("删除", e);
            return ResultBean.fail(101, "删除失败");
        }
    }

}
